package com.tmall.qatest.util;

import com.taobao.hsf.com.caucho.hessian.io.Hessian2Input;
import com.taobao.hsf.com.caucho.hessian.io.Hessian2Output;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * User: Shuffle
 * Date: 13-2-6
 * Time: 上午11:28
 * To change this template use File | Settings | File Templates.
 */
public class MessageUtil {
    public static Serializable byteArray2Object(byte[] body) {
        ByteArrayInputStream bis = null;
        Hessian2Input in = null;

        try {
            bis = new ByteArrayInputStream(body);

            in = new Hessian2Input(bis);

            return (Serializable) in.readObject();
        } catch (IOException e) {
            throw new RuntimeException("deserialize object failed.");
        } finally {
            closeHessianInput(in);
            closeInputStream(bis);
        }
    }

    public static byte[] object2ByteArray(Serializable obj) {
        ByteArrayOutputStream bos = null;
        Hessian2Output out = null;

        try {
            bos = new ByteArrayOutputStream();
            out = new Hessian2Output(bos);

            out.writeObject(obj);
            out.flush();

            return bos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("serialize object failed.");
        } finally {
            closeHessianOutput(out);
            closeOutputStream(bos);
        }
    }

    public static void closeHessianOutput(Hessian2Output out) {
        if (out != null) {
            try {
                out.close();
            } catch (Exception e) {
            }
        }

    }

    public static void closeOutputStream(OutputStream out) {
        if (out != null) {
            try {
                out.close();
            } catch (Exception e) {
            }
        }

    }

    public static void closeInputStream(InputStream bis) {
        if (bis != null) {
            try {
                bis.close();
            } catch (Exception e) {
            }
        }

    }

    public static void closeHessianInput(Hessian2Input in) {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
            }
        }
    }
}
